<template>
    <div class="typewriter">
        <div class="content" :style="contentW">
            <h3 
            class="text" 
            ref="textRef" 
            :style="typewriterStyle.textAnimation">
                {{ typewriterText }}
            </h3>
        </div>
    </div>
</template>

<script setup>
import { poetryApi } from '@/api/public/poetry-api';
// ========================= 组件挂载前 =========================
onBeforeMount(() => {
    getData();
})
// ========================= 组件挂载后 =========================
onMounted(() => {
});

// ========================= 组件卸载后 =========================
onUnmounted(() => {
});

// ========================= 动态style =========================
const typewriterStyle = reactive({
    textAnimation: {
        animation: 'typeAndDelete '+ props.animationTime +
        's steps('+ props.animationSteps +') infinite,blinkCursor 0.5s step-end infinite alternate'
    }
});


const props = defineProps({
    // 文本内容
    text: {
        type: String,
        default: ''
    },

    // 动画持续时间 s
    animationTime: {
        type: Number,
        default: 10,
    },

    // 动画频次
    animationSteps: {
        type: Number,
        default: 16,
    }
});

 // 计算属性来获取文本宽度
 const contentWidth = computed(() => {
    if (textRef.value) {
        return textRef.value.getBoundingClientRect().width;
    };
    return 0;
});

// ========================= 获取数据 =========================
const textRef = ref();
let typewriterText = ref('');
let contentW = ref('')
async function getData() {
    if(props.text) {
        typewriterText.value = props.text
    }else {
        const res = await poetryApi.getScSj();
        typewriterText.value = res.data;
    };
    contentW.value = `width:${contentWidth}px`;
};
</script>

<style lang="scss" scoped>
    @import './typewriter2.scss';
</style>
<!-- 使用动态style设置动画，需要将@keyframes 声明的动画放在全局的样式中。 -->
<style lang="scss">
@keyframes typeAndDelete {
    0%,
    30% {
        width: 0;
    }

    45%,
    75% {
        width: 99%;

    }

    80%,
    100% {
        width: 0;
    }
}
@keyframes blinkCursor {
    50% {
        border-right-color: transparent;
    }
}
</style>